package com.itmk.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        String method = req.getParameter("method");
        String loginUrl = uri +"?method="+method;
        //登录页面、登录请求、验证码不需要拦截
       if(uri.contains("login.jsp") || uri.contains("/Kaptcha") || loginUrl.contains("/login.do?method=login") || uri.contains("http") || uri.contains("lay-config") || uri.contains("bootstrap") || uri.contains("jquery") || uri.contains("layui")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取session
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user != null){
            filterChain.doFilter(servletRequest,servletResponse);
        }else { //强制登录
            rep.sendRedirect("/login.do?method=loginOut");
        }
    }

    @Override
    public void destroy() {

    }
}
